import { fileURLToPath, URL } from 'node:url';

import type { UserConfig, ConfigEnv } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';

import { vitePluginConfig } from './build';
import { transformEnvConfType } from './build/utils';

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const viteEnv = transformEnvConfType(loadEnv(mode, root));
  const { VITE_DROP_CONSOLE, VITE_PORT, VITE_PROXY } = viteEnv;
  return {
    plugins: [
      vue({ include: [/\.vue$/, /\.md$/] }),
      vueJsx(),
      vitePluginConfig(viteEnv),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '#': fileURLToPath(new URL('./types', import.meta.url)),
      },
    },
    server: {
      // https: false,
      host: true,
      // open: true,
      // port: VITE_PORT,
      port: 9520,
      // Load proxy configuration from .env
      // proxy: createProxy(VITE_PROXY),
      /* cors: true, // 启用默认CORS配置
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,POST,OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type,Authorization"
      }, */
      proxy: {
        '/api': {
          changeOrigin: true,
          // target: 'http://192.168.1.111:15001',//发哥本地
          target: 'http://192.168.1.57:9525/sw-scrm',
          rewrite: path => {
            console.log('代理地址：' + path, ',目标地址：' + path.replace(/^\/api/, ''));
            return path.replace(/^\/api/, '');
          },
        },
        '/vipapi': {
          changeOrigin: true,
          target: 'https://dev.senwell.cn/index.php',
          rewrite: path => {
            console.log('vip>>>代理地址：' + path, ',目标地址：' + path.replace(/^\/vipapi/, ''));
            return path.replace(/^\/vipapi/, '');
          },
        },
      },
    },
    esbuild: {
      // 移除日志打印及debugger
      // drop: VITE_DROP_CONSOLE ? ['console', 'debugger'] : [],
    },
    // 处理ant-design-vue 样式文件
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    /* build: {
      rollupOptions: {
        external: ['vue', 'vue-router', 'pinia'],
        output: {
          globals: {
            vue: 'Vue',
            'vue-router': 'VueRouter',
            pinia: 'Pinia'
          }
        }
      }
    }, */
    // 依赖优化 - 预构建
    optimizeDeps: {
      include: ['vue', 'pinia', 'vue-router', 'ant-design-vue/es', '@vueuse/core'],
      // include: ['ant-design-vue/es', '@vueuse/core'],
      // exclude: ['vue', 'vue-router', 'pinia']
    },
    build: {
      outDir: 'dist', // 输出目录
      assetsDir: './source', // 静态资源目录
    },
    // base: basename,
  };
});
